<?php

namespace App\Http\Controllers\Backend;

use App\Repository\Repositories\Interfaces\AdminUserRepository;
use App\Repository\Repositories\Interfaces\MenuRepository;
use App\Repository\Models\PermissionRole;
use App\Repository\Models\RoleUser;
use Illuminate\Http\Request;
use Mockery\CountValidator\Exception;

/**
 * 用户管理控制器
 *
 * @package App\Http\Controllers\Backend
 */
class AdminUserController extends BaseController
{
    private $adminUserRepository;
    private $menuRepository;

    public function __construct(AdminUserRepository $adminUserRepository,MenuRepository $menuRepository)
    {
        parent::__construct();
        $this->adminUserRepository = $adminUserRepository;
        $this->menuRepository = $menuRepository;
    }

    /**
     *用户菜单
     */
    public function menus()
    {
        //获取用户的菜单
        $user = \Auth::user();
        $menus = $this->menuRepository->all()['data'];
        if($user['is_super_admin'] == 1){

        }else{
            $menus = $this->adminUserRepository->getUserMenusByUserModel($user);

        }

        return $this->success('ok',['list' => $menus]);
    }
    
    /**
     * 管理员列表
     *
     * @return \Illuminate\Http\Response1
     */
    public function index()
    {
        $ret = $this->adminUserRepository->with(['roles'])->paginate($this->perPage);
        $data = ['list' => $ret['data'],'page' => $ret['meta']['pagination']];
        return $this->success('ok',$data);
    }

    /**
     * 增加管理员
     *
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        \DB::beginTransaction();
        try {

            $this->validate($request,[
                'name'                  => 'required|unique:admin_users,name',
                'email'                 => 'required|unique:admin_users,email',
                'password'              => 'required',
//                'password_confirmation' => 'required',
                'role_id'               => 'required',
            ],[
                'name.required'                  => '用户名称不能为空',
                'name.unique'                    => '用户名称已存在',
                'email.required'                 => '用户邮箱不能为空',
                'email.unique'                   => '用户邮箱已存在',
                'password.required'              => '用户密码不能为空',
//                'password.confirmed'             => '确认密码不一致',
//                'password_confirmation.required' => '确认密码不能为空',
                'role_id.required'               => '用户角色不能为空',
            ]);
            $data = $request->all();

            // 获取已选择的 role_id
            $role_ids = $data['role_id'];
            unset($data['role_id']);

            $adminUser = $this->adminUserRepository->create($data);
            
            if ($adminUser) {
                $RoleUser = RoleUser::multiCreate($role_ids,$adminUser['data']['admin_user_id']);
                \DB::commit();
                return $this->success('创建管理员成功',$adminUser['data']);
            }else{
                throw new \Exception('保存失败');
            }


        }
        catch (\Exception $e) {
            \DB::rollback(); //事务回滚;
            return $this->error($e->getMessage());
        }
    }

    /**
     *  管理员详情
     *
     * @param  int $id
     *
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        $ret = $this->adminUserRepository->with(['roles'])->find($id);

        // 提取已拥有的角色权限 id
        $ret['data']['roleHas'] = array_column($ret['data']['roles'],'role_id');

        $permissionHas = [];
        if (count($ret['data']['roleHas'])>0){
            $roleIds = $ret['data']['roleHas'];
            $permissionHas = PermissionRole::query()->whereIn('role_id',$roleIds)->get()->toArray();
        }
        // 提取已选角色 id 对应的 操作权限
        $ret['data']['permissionHas'] = array_column($permissionHas,'permission_id');


        return $this->success('ok', $ret['data']);
    }


    /**
     * 修改管理员
     * @param  int                                    $id
     *
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request,$id)
    {
        \DB::beginTransaction();
        try {
            $this->validate($request,[
                'name'     => 'required',
                'email'    => 'required',
                'role'     => 'required',
            ],[
                'name.required'     => '用户名称不能为空',
                'email.required'    => '用户邮箱不能为空',
                'role.required'     => '用户角色不能为空',
            ]);
            $adminUser = $this->adminUserRepository->update($request->only(['name','email','password','avatar']),$id);

            if ($adminUser) {
                $dataAll = $request->all();

                $operate = isset($dataAll['operate'])?$dataAll['operate']:false;
                if ($operate!==false){
                    // 按页面传值修改
                    $operateArr = explode(',',$operate);
                    foreach ($operateArr as $value){
                        $temp = explode('-',$value);
                        $type = $temp[1];
                        $role_id   = $temp[0];
                        switch ($type){
                            case 'add':
                                $saveCreate = [];
                                $saveCreate = ['user_id'=>$id,'role_id'=>$role_id];
                                $create = RoleUser::query()->create($saveCreate)->toArray();
                                break;
                            case 'delete':
                                $delete =  RoleUser::query()->where(['user_id'=>$id,'role_id'=>$role_id])->delete();
                                break;
                        }
                    }

                }
                \DB::commit();
                return $this->success("编辑管理员成功",$adminUser['data']);
            }
        }
        catch (\Exception $e ) {
            \DB::rollback(); //事务回滚;
            return $this->error($e->getMessage());
        }
    }

    /**
     * 删除管理员
     *
     * @param  int $id
     *
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        \DB::beginTransaction();
        try {
            if ($this->adminUserRepository->delete($id)) {
                // 删除用户的时候删除 角色关联 role_user
                $delete =  RoleUser::query()->where('user_id',$id)->delete();
            }
            \DB::commit();
            return $this->success("删除管理员成功");
        }
        catch (\Exception $e) {
            \DB::rollback(); //事务回滚;
            return $this->error($e->getMessage());
        }
    }
    public function log($data,$filename){
        if(empty($filename)){
            $log_filename='C:\Users\admin\Desktop\ecclub.php';
        }
        else{
            $log_filename='C:\Users\admin\Desktop\\'.$filename.'.php';
        }
        // 如果文件夹不存在则创建文件夹
        is_dir(dirname($log_filename)) || mkdir(dirname($log_filename),0777,true);
        // 日志大小
        $max_size=10485760;
        // 判断文件大小做自动删除动作
        if(file_exists($log_filename) && abs(filesize($log_filename))>$max_size){
            // 删除文件
            unlink($log_filename);
        }else{
            // 写日志(第三个参数是系统函数，可以连续写文件不覆盖)
            file_put_contents($log_filename, date("Y-m-d H:i:s",time()+8*60*60)." ".$data."\n", FILE_APPEND);
        }
    }
}
